package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dao.SyUserCollectionMapper;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.entity.AppVersion;
import com.eco.fanliapp.entity.SyUserCollection;
import com.eco.fanliapp.service.ISyUserCollectionService;
import com.eco.fanliapp.service.ITaoBaoService;
import com.eco.fanliapp.service.RedisTemplateService;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo;
import com.eco.fanliapp.vo.respone.ResponeResults;
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.security.Key;
import java.util.*;

/**
 * <p>
 * 收藏表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-08-21
 */
@Service
public class SyUserCollectionServiceImpl extends ServiceImpl<SyUserCollectionMapper, SyUserCollection> implements ISyUserCollectionService {

    @Autowired
    private ITaoBaoService iTaoBaoService;

    @Autowired
    private RedisTemplateService redisTemplateService;

    /**
     * 用收藏列表
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse collectionList(Long userId, Integer pageNum, Integer pageSize) {

        String redisKeyStr = "app_user_collectionList_" + userId;

        Map<String, Map<String, SyUserCollection>> itemMap = this.getRedisCollection(redisKeyStr, userId);

        HashMap map = new HashMap();
        List<SyUserCollection> syUserCollections = new ArrayList<>();
        List<SyUserCollection> syUserCollectionsPage = new ArrayList<>();
        String itemids = "";
        for (String itemkey : itemMap.keySet()) {
            Map<String, SyUserCollection> syUserCollection = itemMap.get(itemkey);
            for (String collect : syUserCollection.keySet()) {
                if (collect.equals("1")) {
                    itemids += itemkey + ",";
                    if (syUserCollection.get(collect) != null) {
                        syUserCollections.add(syUserCollection.get(collect));
                    }
                }
            }
        }

        List<Long> list = new ArrayList<>();
        ServerResponse<List<TbkItemInfoGetInfo.NTbkItem>> items = iTaoBaoService.getSearchItemIdDetail(itemids);
        if (items != null && items.getStatus() == 200 && items.getData() != null) {
            List<TbkItemInfoGetInfo.NTbkItem> nTbkItems = items.getData();
            for (TbkItemInfoGetInfo.NTbkItem nTbkItem : nTbkItems) {
                list.add(nTbkItem.getNumIid());
            }
        }
        for (SyUserCollection collection : syUserCollections) {
            if (list.contains(collection.getGoodsId())) {
                collection.setJumpType(1);
            } else {
                collection.setJumpType(0);
            }
        }
        Collections.sort(syUserCollections);
        for (int i = (pageNum - 1) * pageSize; i < ((pageNum - 1) * pageSize + pageSize > syUserCollections.size() ? syUserCollections.size() : (pageNum - 1) * pageSize + pageSize); i++) {
            syUserCollectionsPage.add(syUserCollections.get(i));
        }

        if (syUserCollectionsPage.size() == 0) {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多收藏了");
        }
        map.put("collectList",syUserCollectionsPage);
        return ServerResponse.createBySuccess(200, "获取收藏商品成功", map);
    }

    /**
     * 获取缓存中的redis信息，如果不存在从数据库中查询并插入redis中，redis有效期30分钟
     * @param redisKeyStr
     * @param userId
     * @return
     */
    @Override
    public Map<String, Map<String, SyUserCollection>> getRedisCollection(String redisKeyStr, Long userId) {

        Map<String, Map<String, SyUserCollection>> itemMap = null;
        if (redisTemplateService.hasKey(redisKeyStr)) {
            itemMap = redisTemplateService.getTByKey(redisKeyStr, Map.class);
        }
        if (itemMap == null || itemMap.size() <= 0) {
            itemMap = new HashMap<>();
            QueryWrapper<SyUserCollection> syUserCollectionWrapper = new QueryWrapper<>();
            syUserCollectionWrapper.eq("user_id", userId);
//            syUserCollectionWrapper.eq("enable", 1);
//            syUserCollectionWrapper.eq("deleted", 0);
            syUserCollectionWrapper.orderByDesc("update_time");
            List<SyUserCollection> syUserCollectionList = this.list(syUserCollectionWrapper);
            if (syUserCollectionList != null && syUserCollectionList.size() > 0) {
                for (SyUserCollection syUserCollection : syUserCollectionList) {
                    Map<String, SyUserCollection> zz_item = new HashMap<>();
                    if (syUserCollection.getDeleted() == null || syUserCollection.getDeleted() == 1 || syUserCollection.getEnable() == null || syUserCollection.getEnable() == 0) {
                        zz_item.put("0", syUserCollection);
                    } else {
                        zz_item.put("1", syUserCollection);
                    }

                    itemMap.put(syUserCollection.getGoodsId().toString(), zz_item);
                }
            }
            redisTemplateService.set(redisKeyStr, itemMap, 60 * 60);
        }
        return itemMap;
    }

    public SyUserCollection collectionList(String itemId, Long userId) {
        ServerResponse<ResponeResults> response = iTaoBaoService.getHdkSearchItemIdDetail(itemId, userId, null, "0",1,null);//1代表收藏
        if (response.getStatus() == 200 && response.getData() != null) {
            List<ResponeResults.DataBean> dataBeans = response.getData().getData();
            if (dataBeans != null && dataBeans.size() == 1) {
                for (ResponeResults.DataBean bean : dataBeans) {
                    SyUserCollection syUserCollection = new SyUserCollection();
                    syUserCollection.setGoodsId(Long.valueOf(itemId));
                    syUserCollection.setUserId(userId);
                    if (bean.getItemShortTitle().isEmpty() || bean.getItemShortTitle().equals("")) {
                        syUserCollection.setGoodsName(bean.getItemTitle());
                    }
                    syUserCollection.setGoodsName(bean.getItemShortTitle());
                    syUserCollection.setGoodsPicture(bean.getItempictUrl());
                    syUserCollection.setGoodsCoupon(new BigDecimal(bean.getCouponMoney()));
                    syUserCollection.setGoodsPrice(new BigDecimal(bean.getItemPrice()));
                    syUserCollection.setGoodsSubsidies(bean.getFanliMoney());
                    syUserCollection.setBelongDate(new Date());
                    syUserCollection.setGoodsTkPrice(bean.getTheirPriceMoney());
                    if (bean.getItemType().equalsIgnoreCase("B")) {
                        //2天猫
                        syUserCollection.setGoodsShopType(2);
                    } else {
                        //1淘宝
                        syUserCollection.setGoodsShopType(1);
                    }
                    syUserCollection.setEnable(1);
                    syUserCollection.setDeleted(0);
                    syUserCollection.setCreateTime(new Date());
                    syUserCollection.setUpdateTime(new Date());
                    return syUserCollection;
                }
            }
        }
        return null;
    }

    /**
     * 是否已经收藏
     * @param userId
     * @param itemId
     * @return
     */
    @Override
    public ServerResponse goodsCollection(Long userId, Long itemId) {

        String redisKeyStr = "app_user_collectionList_" + userId;
        Map<String, Map<String, SyUserCollection>> itemMap = this.getRedisCollection(redisKeyStr, userId);
        String userKey = itemId.toString();

        HashMap map = new HashMap();
        if (itemMap != null && itemMap.size() > 0) {
            if (itemMap.containsKey(userKey)) {
                Map<String, SyUserCollection> syUserCollectionMap = itemMap.get(userKey);
                for (String collect : syUserCollectionMap.keySet()) {
                    if ("0".equals(collect)) {
                        map.put("collect", 0);
                        return ServerResponse.createBySuccess("没有收藏", map);
                    }
                    if ("1".equals(collect)) {
                        map.put("collect", 1);
                        return ServerResponse.createBySuccess("已经收藏", map);
                    }
                }

            }
        }
        map.put("collect", 0);
        return ServerResponse.createBySuccess("没有收藏", map);
    }

    /**
     * 取消收藏
     * @param userId
     * @param itemId
     * @param type
     * @return
     */
    @Override
    public ServerResponse cancelCollection(Long userId, Long itemId, Integer type) {
        String redisKeyStr = "app_user_collectionList_" + userId;
        Map<String, Map<String, SyUserCollection>> itemMap = this.getRedisCollection(redisKeyStr, userId);
        String userKey = itemId.toString();

        HashMap map = new HashMap();

        if (itemMap != null && itemMap.size() > 0 && itemMap.containsKey(userKey)) {

            Map<String, SyUserCollection> syUserCollectionMap = itemMap.get(userKey);

            for (String collect : syUserCollectionMap.keySet()) {
                if ("1".equals(collect)) {

                    SyUserCollection syUserCollection = collectionList(itemId.toString(), userId);

                    HashMap collectGoods = new HashMap();
                    collectGoods.put("0", syUserCollection);
                    itemMap.put(userKey, collectGoods);
                    redisTemplateService.set(redisKeyStr, itemMap, 60 * 60);

                    String save_update_key = "app_user_collection_saveOrUpdate";
                    //记录更新的数据
                    if (redisTemplateService.hasKey(save_update_key)) {
                        Map<String, String> saveOrUpdateMap = redisTemplateService.getTByKey(save_update_key, Map.class);
                        saveOrUpdateMap.put(userId.toString() + ":" + itemId.toString(), "0");
                        redisTemplateService.set(save_update_key, saveOrUpdateMap, 60L * 60 * 24);
                    } else {
                        HashMap saveOrUpdate = new HashMap();
                        saveOrUpdate.put(userId.toString() + ":" + itemId.toString(), "0");
                        redisTemplateService.set(save_update_key, saveOrUpdate, 60L * 60 * 24);
                    }

                } else {
                    map.put("collect", 0);
                    return ServerResponse.createBySuccess("取消收藏成功", map);
                }
            }
        }else {
            return ServerResponse.createByErrorMessage("还未收藏");
        }

        map.put("collect", 0);
        return ServerResponse.createBySuccess("取消收藏成功", map);

    }
    /**
     * 前往收藏
     * @param userId
     * @param itemId
     * @param type
     * @return
     */
    @Override
    public ServerResponse saveCollection(Long userId, Long itemId, Integer type) {
        String redisKeyStr = "app_user_collectionList_" + userId;
        Map<String, Map<String, SyUserCollection>> itemMap = this.getRedisCollection(redisKeyStr, userId);
        String userKey = itemId.toString();

        HashMap map = new HashMap();

        if (itemMap != null && itemMap.size() > 0 && itemMap.containsKey(userKey)) {

            Map<String, SyUserCollection> syUserCollectionMap = itemMap.get(userKey);

            for (String collect : syUserCollectionMap.keySet()) {
                if ("0".equals(collect)) {

                    SyUserCollection syUserCollection = collectionList(itemId.toString(), userId);

//                    SyUserCollection syUserCollectionOld = syUserCollectionMap.get(collect);
//                    SyUserCollection syUserCollectionNew = new SyUserCollection();
//                    syUserCollectionNew.setEnable(1);
//                    syUserCollectionNew.setDeleted(0);
//                    syUserCollectionNew.setTableId(syUserCollectionOld.getTableId());
//                    boolean flag = this.updateById(syUserCollectionNew);

                    HashMap collectGoods = new HashMap();
                    collectGoods.put("1", syUserCollection);
                    itemMap.put(userKey, collectGoods);
                    redisTemplateService.set(redisKeyStr, itemMap, 60 * 60);

                } else {
                    map.put("collect", 1);
                    return ServerResponse.createBySuccess("已收藏", map);
                }
            }
        }else {
            SyUserCollection syUserCollection = collectionList(itemId.toString(), userId);
            HashMap collectGoods = new HashMap();
            collectGoods.put("1", syUserCollection);

            itemMap.put(userKey, collectGoods);
            redisTemplateService.set(redisKeyStr, itemMap, 60 * 60);

        }

        String save_update_key = "app_user_collection_saveOrUpdate";
        //记录更新的数据
        if (redisTemplateService.hasKey(save_update_key)) {
            Map<String, String> saveOrUpdateMap = redisTemplateService.getTByKey(save_update_key, Map.class);
            saveOrUpdateMap.put(userId.toString() + ":" + itemId.toString(), "1");
            redisTemplateService.set(save_update_key, saveOrUpdateMap, 60L * 60 * 24);
        } else {
            HashMap saveOrUpdate = new HashMap();
            saveOrUpdate.put(userId.toString() + ":" + itemId.toString(), "1");
            redisTemplateService.set(save_update_key, saveOrUpdate, 60L * 60 * 24);
        }

        map.put("collect", 1);
        return ServerResponse.createBySuccess("收藏成功", map);
    }

}
